package chapter3;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

/**
 * @author : Neo
 * @version : V1.0
 * @date :2017/11/18 11:52
 * @description :
 */
public class NioServer {
	public Selector selector;
	public void initServer(int port) throws Exception{
		ServerSocketChannel serverChannel=ServerSocketChannel.open();
		serverChannel.configureBlocking(false);
		serverChannel.socket().bind(new InetSocketAddress(port));
		this.selector = Selector.open();
		serverChannel.register(this.selector, SelectionKey.OP_ACCEPT);
	}
	public void listen() throws Exception {
		System.out.println("服务器启动成功");
		while (true) {
			selector.select();
			Iterator ite = this.selector.selectedKeys()
										.iterator();
			while (ite.hasNext()) {
				SelectionKey key = (SelectionKey) ite.next();
				ite.remove();
				if (key.isAcceptable()) {
					ServerSocketChannel server = (ServerSocketChannel) key.channel();
					SocketChannel channel = server.accept();
					channel.configureBlocking(false);
					channel.write(ByteBuffer.wrap(new String("1234567890").getBytes()));
					channel.register(this.selector, SelectionKey.OP_READ);
				}
				else if(key.isReadable()){
					read(key);
				}

			}
		}


	}

	private void read(SelectionKey key) throws Exception {

//		SocketChannel channel = (SocketChannel) key.channel();
//		ByteBuffer buffer = ByteBuffer.allocate(10);
//		channel.read(buffer);
//
//		//        转为字符串
//		byte[] data = buffer.array();
//		String msg=new String(data).trim();
//		System.out.println("服务端收到信息:"+msg);
////		msg="回传信息=----";
//
//
//
//		ByteBuffer outbuffer = ByteBuffer.wrap(msg.getBytes());
//		channel.write(outbuffer);


		SocketChannel channel = (SocketChannel) key.channel();
		ByteBuffer buffer = ByteBuffer.allocate(100);
//        从CH中读取信息
		channel.read(buffer);
//        转为字符串
		byte[] data = buffer.array();
		String msg=new String(data).trim();
		System.out.println("服务端收到信息:"+msg);
		msg="回传信息=----";

		ByteBuffer outbuf=ByteBuffer.wrap(msg.getBytes());
//        将消息送给客户端
		channel.write(outbuf);


	}


	public static void main(String[] args) throws Exception {
		NioServer server = new NioServer();
		server.initServer(8100);
		server.listen();
	}
}
